﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ReaderB;

namespace TS_XY_Train_Repaire.ToolSystem
{
    public partial class Tool_System_OrderDetail_Form : DevExpress.XtraEditors.XtraForm
    {
        public TS_Order m_oOrder = new TS_Order();
        private DataTable m_oDT = new DataTable();

        private List<string> m_listRFID = new List<string>();
        private CRfid m_rfid = new CRfid();
        private System.Windows.Forms.Timer m_tTimer = new System.Windows.Forms.Timer();//实例化Timer类，设置间隔时间为10000毫秒；

        public Tool_System_OrderDetail_Form()
        {
            InitializeComponent();
        }

        public TS_Order OOrder { get => m_oOrder; set => m_oOrder = value; }

        private void Tool_System_OrderDetail_Form_Load(object sender, EventArgs e)
        {
            te_id.Text = m_oOrder.IID.ToString();
            te_propos.Text = m_oOrder.SProposName;
            if (m_oOrder.SProposTime != DateTime.MinValue)
                te_propostime.Text = m_oOrder.SProposTime.ToString();
            te_send.Text = m_oOrder.SSendName;
            if (m_oOrder.SSendTime != DateTime.MinValue)
                te_sendtime.Text = m_oOrder.SSendTime.ToString();
            te_recive.Text = m_oOrder.SReciveName;
            if (m_oOrder.SReciveTime != DateTime.MinValue)
                te_recivetime.Text = m_oOrder.SReciveTime.ToString();

            btn_lern.Visible = false;

            te_status.Text = Utility.GetOrderStateString(m_oOrder.IStatus);
            if (m_oOrder.IStatus == OrderStatus.Apply)
            {
                btn_lern.Visible = true;
                btn_lern.Text = "确认借出";
            }
            else if (m_oOrder.IStatus == OrderStatus.Return)
            {
                btn_lern.Visible = true;
                btn_lern.Text = "确认归还";
            }

            _LoadGrid();

            if (m_oOrder.IStatus == OrderStatus.Apply
                || m_oOrder.IStatus == OrderStatus.Return)
            {
                if (m_rfid.Init())
                {
                    // 开启定时器
                    m_tTimer.Interval = 1000;
                    m_tTimer.Tick += new EventHandler(timer_Tick);
                    m_tTimer.Enabled = true;
                }
                else
                {
                    MessageBox.Show("打开rfid串口失败!");
                }
            }
        }

        // 加订单工具列表
        private void _LoadGrid()
        {
            try
            {
                m_oDT = ToolDataMgr.GetInstance().GetOrderDetail(m_oOrder.IID);

                m_oDT.Columns.Add(new DataColumn("f_statusname"));
                if (m_oOrder.IStatus == OrderStatus.Apply)
                {
                    //
                    m_oDT.Columns.Add(new DataColumn("f_toolconfirm", typeof(bool)));
                }
                else
                {
                    gridView1.Columns["f_toolconfirm"].Visible = false;
                }

                foreach (DataRow dataRow in m_oDT.Rows)
                {
                    int iStatus = int.Parse(dataRow["f_statetype"].ToString());

                    dataRow["f_statusname"] = Utility.GetToolStateString((ToolStatus)iStatus);

                    if (m_oOrder.IStatus == OrderStatus.Apply)
                    {
                        dataRow["f_toolconfirm"] = false;
                    }
                }

                gc_Main.DataSource = m_oDT;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);

                gc_Main.DataSource = null;
                gc_Main.Refresh();
            }
        }

        // 根据RFID更新状态
        private void UpdateDataTable(List<string> listRFID)
        {
            if (listRFID.Count <= 0)
                return;

            foreach (DataRow dataRow in m_oDT.Rows)
            {
                string sRFID = dataRow["f_rfid"].ToString();
                if (listRFID.Contains(sRFID))
                {
                    if (m_oOrder.IStatus == OrderStatus.Apply)
                    {
                        // 修改checkbox状态
                        dataRow["f_toolconfirm"] = true;
                    }
                    else if (m_oOrder.IStatus == OrderStatus.Return)
                    {
                        // 修改工具状态
                        if ((ToolStatus)(Utility.GetToolStatueInt(dataRow["f_statusname"].ToString())) == ToolStatus.Borrow)
                            dataRow["f_statusname"] = Utility.GetToolStateString(ToolStatus.Normal);
                    }
                }
            }

            gc_Main.DataSource = m_oDT;
        }

        private void btn_lern_Click(object sender, EventArgs e)
        {
            // 修改订单状态
            if (m_oOrder.IStatus == OrderStatus.Apply)
            {
                m_oOrder.IStatus = OrderStatus.Confirm;
                m_oOrder.ISendID = int.Parse(TS_Win_Locomotive_MainForm.pUserInfoMain.UserCode);
                m_oOrder.SSendTime = DateTime.Now;
            }
            else
            {
                UpdateToolStatus();

                m_oOrder.IStatus = OrderStatus.Finish;
                m_oOrder.IReciveID = int.Parse(TS_Win_Locomotive_MainForm.pUserInfoMain.UserCode);
                m_oOrder.SReciveTime = DateTime.Now;
            }

            if (ToolDataMgr.GetInstance().ModifyOrder(m_oOrder))
                this.DialogResult = DialogResult.OK;
            else
                this.DialogResult = DialogResult.Cancel;
        }

        // 更新工具状态到数据库
        private bool UpdateToolStatus()
        {
            foreach (DataRow dataRow in m_oDT.Rows)
            {
                int iToolID = int.Parse(dataRow["f_toolid"].ToString());
                int iStatus = Utility.GetToolStatueInt(dataRow["f_statusname"].ToString());
                int iOldStatus = int.Parse(dataRow["f_statetype"].ToString());

                if (iStatus != iOldStatus && iStatus >= 0)
                {
                    // 更新工具状态
                    ToolDataMgr.GetInstance().ModifyToolStatus(iToolID, iStatus);
                }
            }

            return true;
        }

        private void Tool_System_OrderDetail_Form_FormClosing(object sender, FormClosingEventArgs e)
        {
            m_rfid.UnInit();
            m_tTimer.Enabled = false;
        }

        void timer_Tick(object sender, EventArgs e)
        {
            lock (this)
            {
                List<string> listRFID = new List<string>();
                if (!m_rfid.GetRFID(ref listRFID))
                    return;

                if (listRFID.All(m_listRFID.Contains) && listRFID.Count == m_listRFID.Count)
                    return;

                //更新本地状态
                m_listRFID = listRFID;
                UpdateDataTable(m_listRFID);
            }
        }
    }
}